/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller;

import com.thienloc.omap.entity.OmapUser;
import com.thienloc.omap.session.OmapUserFacade;
import com.thienloc.omap.util.Constant;
import com.thienloc.omap.util.JsfUtil;
import com.thienloc.omap.util.SecurityUtil;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class OmapUserBean extends AbstractCrudBean {

    @EJB
    private OmapUserFacade facade;
    private OmapUser selected;
    private List<OmapUser> list;
    private String confirmPassword;
    private String password;
    private String currentPassword;

    @Override
    protected void validateForm() throws Exception {
        if (!confirmPassword.equals(password)) {
            throw new Exception("Xác nhận mật khẩu không đúng");
        }
    }

    @Override
    protected Logger getLogger() {
        return LoggerFactory.getLogger(OmapUserBean.class);
    }

    @Override
    protected void resetToCreateFormAction() throws Exception {
        list = facade.findAll();
        selected = new OmapUser();
        password = "";
        confirmPassword = "";
        edit = false;
        view = false;
    }

    @Override
    protected void findSelected(int id) throws Exception {
        selected = facade.find(id);
        SecurityUtil.isMatched(password, password, password, id);
    }

    public void changePassword() {
        try {
            boolean equal = SecurityUtil.isMatched(currentPassword, selected.getPassword(), selected.getPasswordSalt(), Constant.PASSWORD_ITERATION_NUM);
            if (!equal) {
                throw new Exception("Bạn đã nhập sai mật khẩu hiện tại");
            } else {
                if (!confirmPassword.equals(password)) {
                    throw new Exception("Xác nhận mật khẩu không trùng khớp với mật khẩu mới");
                } else {
                    String salt = SecurityUtil.generateSalt();
                    byte[] hash = SecurityUtil.getHash(Constant.PASSWORD_ITERATION_NUM, password, SecurityUtil.base64ToByte(salt));
                    String passwordHash = SecurityUtil.byteToBase64(hash);
                    selected.setPassword(passwordHash);
                    selected.setPasswordSalt(salt);
                    selected.setLastPwdChangeDate(new Date());
                    facade.edit(selected);

                    JsfUtil.addSuccessMessage("Thành công!", "Đã sửa đổi mật khẩu");
                }
            }
        } catch (Exception ex) {
            logAndNotifyError(ex);
        }
    }

    @Override
    protected void createSelected() throws Exception {
        String salt = SecurityUtil.generateSalt();
        byte[] hash = SecurityUtil.getHash(Constant.PASSWORD_ITERATION_NUM, password, SecurityUtil.base64ToByte(salt));
        String passwordHash = SecurityUtil.byteToBase64(hash);
        selected.setPassword(passwordHash);
        selected.setPasswordSalt(salt);
        selected.setCreatedDate(new Date());

        facade.create(selected);
        resetToCreateForm();
        JsfUtil.addSuccessMessage("Thành công!", "Đã thêm mới thành công một bản ghi");
    }

    @Override
    protected void editSelected() throws Exception {
        String salt = SecurityUtil.generateSalt();
        byte[] hash = SecurityUtil.getHash(Constant.PASSWORD_ITERATION_NUM, password, SecurityUtil.base64ToByte(salt));
        String passwordHash = SecurityUtil.byteToBase64(hash);
        selected.setPassword(passwordHash);
        selected.setPasswordSalt(salt);

        facade.edit(selected);
        resetToCreateForm();
        JsfUtil.addSuccessMessage("Thành công!", "Đã cập nhật thành công một bản ghi");
    }

    public void editMyAccount() {
        try {
            facade.edit(selected);
            JsfUtil.addSuccessMessage("Thành công!", "Đã thay đổi thông tin tài khoản");
        } catch (Exception ex) {
            logAndNotifyError(ex);
        }
    }

    @Override
    protected void removeSelected() throws Exception {
        Integer id = Integer.parseInt(JsfUtil.getRequestParameter("id"));
        selected = facade.find(id);
        facade.remove(selected);

        resetToCreateForm();
        JsfUtil.addSuccessMessage("Thành công!", "Đã xóa thành công một bản ghi");
    }

    @Override
    protected void prepareViewAction() throws Exception {
        view = true;
        edit = false;
        Integer id = Integer.parseInt(JsfUtil.getRequestParameter("id"));
        selected = facade.find(id);
    }

    @Override
    protected void prepareEditAction() throws Exception {
        view = false;
        edit = true;
        Integer id = Integer.parseInt(JsfUtil.getRequestParameter("id"));
        selected = facade.find(id);
    }

    public void goToMyAccount() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        this.selected = (OmapUser) session.getAttribute("user");
    }

    public List<OmapUser> getList() {
        return list;
    }

    public void setList(List<OmapUser> list) {
        this.list = list;
    }

    public OmapUser getSelected() {
        return selected;
    }

    public void setSelected(OmapUser selected) {
        this.selected = selected;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCurrentPassword() {
        return currentPassword;
    }

    public void setCurrentPassword(String currentPassword) {
        this.currentPassword = currentPassword;
    }
}
